package com.xps.charmingshop.view.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.jude.utils.JUtils;
import com.xps.charmingshop.R;
import com.xps.charmingshop.bean.ObtainMenuBean;
import com.xps.charmingshop.bean.UpdateMenuBean;
import com.xps.charmingshop.bean.VerificationBean;
import com.xps.charmingshop.date.net.UserNetWorks;
import com.xps.charmingshop.servicer.DishService;
import com.xps.charmingshop.servicer.DishServiceImpl;
import com.xps.charmingshop.servicer.UserService;
import com.xps.charmingshop.servicer.UserServiceImpl;
import com.xps.charmingshop.utils.DensityUtil;
import com.xps.charmingshop.utils.SharedPreferencesUtils;
import com.xps.charmingshop.view.base.BaseActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import rx.Subscriber;

import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by MI on 2018/1/31.
 */

public class AddMenuActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {
    @BindView(R.id.actionbar_iv_back)
    ImageView actionbarIvBack;
    @BindView(R.id.actionbar_tv_title)
    TextView actionbarTvTitle;
    @BindView(R.id.Text_AddProductName)
    EditText TextAddProductName;
    @BindView(R.id.Text_AddClassificationOne)
    TextView TextAddClassificationOne;
    @BindView(R.id.Text_ClassificationTwo)
    TextView TextClassificationTwo;
    @BindView(R.id.Text_AddOriginalPrice)
    EditText TextAddOriginalPrice;
    @BindView(R.id.Text_AddDiscount)
    EditText TextAddDiscount;
    @BindView(R.id.Text_AddConcessionalRate)
    EditText TextAddConcessionalRate;
    @BindView(R.id.Image_Add1)
    ImageView ImageAdd1;
    @BindView(R.id.Image_Add2)
    ImageView ImageAdd2;
    @BindView(R.id.Image_Add3)
    ImageView ImageAdd3;
    @BindView(R.id.Text_AddIntroduce)
    TextView TextAddIntroduce;
    @BindView(R.id.AddMust_Add)
    TextView AddMustAdd;
    @BindView(R.id.Text_AddMandatory)
    LinearLayout TextAddMandatory;
    @BindView(R.id.AddOptional_Add)
    TextView AddOptionalAdd;
    @BindView(R.id.Text_AddOptional)
    LinearLayout TextAddOptional;
    @BindView(R.id.Button_AddMenu)
    Button ButtonAddMenu;

    View OptionalView;
    Dialog OptionalDialog;
    EditText Optional_Name;
    EditText Optional_Price;
    ViewGroup.MarginLayoutParams Optionalparams;
    TextView Button_Optional;
    String[] Optional = {};
    List<String> OptionalArray;

    View MustView;
    Dialog MustDialog;
    EditText Must_Name;
    EditText Must_Price;
    TextView Button_OK;
    String[] str = {};
    List<String> strArray;

    AlertDialog dialog;
    LayoutInflater layoutInflater;
    LinearLayout Layout_Classification;
    View longinDialogView;

    String dish_sort_id;

    String[] Imagestr = {};
    List<String> ImageArray;

    String StrImage_Add1;
    String StrImage_Add2;
    String StrImage_Add3;

    private TakePhoto takePhoto;
    private CropOptions cropOptions;  //裁剪参数
    private CompressConfig compressConfig;  //压缩参数
    private Uri imageUri;  //图片保存路径
    private InvokeParam invokeParam;
    private DishService userService = new DishServiceImpl();

    Dialog bottomDialog;
    ViewGroup.MarginLayoutParams params;
    TextView XiCe_pickPhoto;
    TextView XiJi_takePhoto;
    TextView cancel_TextView;

    String StrChoice;

    @Override
    protected int getLayout() {
        return R.layout.activity_addmenu;
    }

    @Override
    protected void setData() {
        actionbarTvTitle.setText("添加菜品");
        actionbarTvTitle.setTextColor(getResources().getColor(R.color.white));
    }

    @Override
    protected void init(Bundle inBundle) {
        ButterKnife.bind(this);
        getAddObtainMenu();
        initData();
        OptionalArray = new ArrayList<String>();
        OptionalArray.addAll(Arrays.asList(Optional));
        OptionalDialog = new Dialog(this, R.style.BottomDialog);
        OptionalView = LayoutInflater.from(this).inflate(R.layout.dialog_optional, null);
        OptionalDialog.setContentView(OptionalView);
        Optionalparams = (ViewGroup.MarginLayoutParams) OptionalView.getLayoutParams();
        Optionalparams.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 16f);
        Optionalparams.bottomMargin = DensityUtil.dp2px(this, 8f);
        OptionalView.setLayoutParams(Optionalparams);
        OptionalDialog.setCanceledOnTouchOutside(true);
        OptionalDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        Optional_Name = OptionalView.findViewById(R.id.Optional_Name);
        Optional_Price = OptionalView.findViewById(R.id.Optional_Price);
        Button_Optional = OptionalView.findViewById(R.id.Button_Optional);
        Button_Optional.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((Optional_Name.getText().toString().equals("") || Optional_Name.getText().toString() == null) && (Optional_Price.getText().toString().equals("") || Optional_Price.getText().toString() == null)) {
                    JUtils.Toast("添加失败");
                } else {
                    showOptionalDialog();
                }
                OptionalDialog.dismiss();
            }
        });


        strArray = new ArrayList<String>();
        strArray.addAll(Arrays.asList(str));
        MustDialog = new Dialog(this, R.style.BottomDialog);
        MustView = LayoutInflater.from(this).inflate(R.layout.dialog_must, null);
        MustDialog.setContentView(MustView);
        params = (ViewGroup.MarginLayoutParams) MustView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 16f);
        params.bottomMargin = DensityUtil.dp2px(this, 8f);
        MustView.setLayoutParams(params);
        MustDialog.setCanceledOnTouchOutside(true);
        MustDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        Must_Name = MustView.findViewById(R.id.Must_Name);
        Must_Price = MustView.findViewById(R.id.Must_Price);
        Button_OK = MustView.findViewById(R.id.Button_OK);
        Button_OK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((Must_Name.getText().toString().equals("") || Must_Name.getText().toString() == null) && (Must_Price.getText().toString().equals("") || Must_Price.getText().toString() == null)) {
                    JUtils.Toast("添加失败");
                } else {
                    showMustDialog();
                }
                MustDialog.dismiss();
            }
        });

        layoutInflater = LayoutInflater.from(AddMenuActivity.this);
        AlertDialog.Builder builder = new AlertDialog.Builder(AddMenuActivity.this);
        dialog = builder.create();
        longinDialogView = layoutInflater.inflate(R.layout.dialog_classification, null);
        dialog.setView(longinDialogView);
        Layout_Classification = longinDialogView.findViewById(R.id.Layout_Classification);


        ImageArray = new ArrayList<String>();
        ImageArray.addAll(Arrays.asList(Imagestr));
        bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_photo, null);
        bottomDialog.setContentView(contentView);
        params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 16f);
        params.bottomMargin = DensityUtil.dp2px(this, 8f);
        contentView.setLayoutParams(params);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        XiCe_pickPhoto = (TextView) contentView.findViewById(R.id.XiCe_pickPhoto);
        XiCe_pickPhoto.setText("相机");
        XiJi_takePhoto = (TextView) contentView.findViewById(R.id.XiJi_takePhoto);
        XiJi_takePhoto.setText("相册");
        cancel_TextView = (TextView) contentView.findViewById(R.id.cancel_TextView);
        layoutInflater = LayoutInflater.from(AddMenuActivity.this);


    }

    @OnClick({R.id.actionbar_iv_back, R.id.Text_AddProductName, R.id.Text_AddClassificationOne, R.id.Text_ClassificationTwo, R.id.Text_AddOriginalPrice, R.id.Text_AddDiscount, R.id.Text_AddConcessionalRate, R.id.Image_Add1, R.id.Image_Add2, R.id.Image_Add3, R.id.Text_AddIntroduce, R.id.AddMust_Add, R.id.Text_AddMandatory, R.id.AddOptional_Add, R.id.Text_AddOptional, R.id.Button_AddMenu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.actionbar_iv_back:
                finish();
                break;
            case R.id.Text_AddClassificationOne:
                dialog.show();
                break;
            case R.id.Image_Add1:
                StrChoice = "1";
                OnClick();
                break;
            case R.id.Image_Add2:
                StrChoice = "2";
                OnClick();
                break;
            case R.id.Image_Add3:
                StrChoice = "3";
                OnClick();
                break;
            case R.id.AddMust_Add:
                MustDialog.show();
                break;
            case R.id.AddOptional_Add:
                OptionalDialog.show();
                break;
            case R.id.Button_AddMenu:
                if (ableGoNext())
                    getAddMenu();
                break;
        }
    }

    private void showOptionalDialog() {
        OptionalArray.add("{\"optional_name\":\"" + Optional_Name.getText().toString() + "\",\"optional_price\":\"" + Optional_Price.getText().toString() + "\"}");
        addOptionalItem(Optional_Name.getText().toString(), "{\"optional_name\":\"" + Optional_Name.getText().toString() + "\",\"optional_price\":\"" + Optional_Price.getText().toString() + "\"}", TextAddOptional);
        System.out.println(OptionalArray);
        Optional_Name.setText("");
        Optional_Price.setText("");
        addDividerLine(TextAddOptional);
    }

    public void addOptionalItem(String str, final String set, LinearLayout ll_lv) {
        View view = LayoutInflater.from(AddMenuActivity.this).inflate(R.layout.classification_item, null);
        final TextView Text_Classification = view.findViewById(R.id.Text_Classification);
        final RelativeLayout YZ = view.findViewById(R.id.YC);
        TextView tv_delete = view.findViewById(R.id.tv_delete);
        Text_Classification.setText(str);
        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < OptionalArray.size(); i++) {
                    if (OptionalArray.get(i).equals(set))
                        OptionalArray.remove(i);
                }
                YZ.setVisibility(View.GONE);
                System.out.println(OptionalArray);
            }
        });
        ll_lv.addView(view);
    }

    public void addDividerLine(LinearLayout ll_lv) {
        View v = new View(AddMenuActivity.this);
        v.setAlpha(0.5f);
        v.setBackgroundColor(AddMenuActivity.this.getResources().getColor(R.color.dialogplus_card_shadow));
        v.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1));
        ll_lv.addView(v);
    }

    private void showMustDialog() {
        strArray.add("{\"must_name\":\"" + Must_Name.getText().toString() + "\",\"must_price\":\"" + Must_Price.getText().toString() + "\"}");
        addMustItem(Must_Name.getText().toString(), "{\"must_name\":\"" + Must_Name.getText().toString() + "\",\"must_price\":\"" + Must_Price.getText().toString() + "\"}", TextAddMandatory);
        System.out.println(strArray);
        Must_Name.setText("");
        Must_Price.setText("");
        addDividerLine(TextAddMandatory);
    }

    public void addMustItem(String str, final String set, LinearLayout ll_lv) {
        View view = LayoutInflater.from(AddMenuActivity.this).inflate(R.layout.classification_item, null);
        final TextView Text_Classification = view.findViewById(R.id.Text_Classification);
        TextView tv_delete = view.findViewById(R.id.tv_delete);
        final RelativeLayout YZ = view.findViewById(R.id.YC);
        Text_Classification.setText(str);
        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < strArray.size(); i++) {
                    if (strArray.get(i).equals(set))
                        strArray.remove(i);
                }
                YZ.setVisibility(View.GONE);
                System.out.println(strArray);
            }
        });
        ll_lv.addView(view);
    }


    public void getAddObtainMenu() {
        String user_token = SharedPreferencesUtils.getString("user_token", "String", null);
        UserNetWorks.getAddObtainMenu(user_token, new Subscriber<ObtainMenuBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(ObtainMenuBean obtainMenuBean) {
                if (obtainMenuBean.getReturn_code().equals("SUCCESS")) {
                    List<ObtainMenuBean.ReturnBodyBean> list = obtainMenuBean.getReturn_body();
                    if (list != null && list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            addOrderItem(list.get(i), Layout_Classification);
                            addDividerLine(Layout_Classification);
                            TextAddClassificationOne.setText(list.get(i).getSort_name());
                            dish_sort_id = list.get(i).getSort_id();
                        }
                    }
                }
            }
        });
    }

    /**
     * 分类
     * addOrderItem(DingDanBean.ReturnBodyBean dataBean)
     */
    public void addOrderItem(final ObtainMenuBean.ReturnBodyBean dataBean, LinearLayout ll_lv) {
        View view = LayoutInflater.from(AddMenuActivity.this).inflate(R.layout.classification_item_fan, null);
        TextView Text_Classification = view.findViewById(R.id.Text_Classification);
        Text_Classification.setText(dataBean.getSort_name());
        Text_Classification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextAddClassificationOne.setText(dataBean.getSort_name());
                dish_sort_id = dataBean.getSort_id();
                dialog.dismiss();
            }
        });
        ll_lv.addView(view);
    }

    public void getAddMenu() {
        String user_token = SharedPreferencesUtils.getString("user_token", "String", null);
        UserNetWorks.getAddMenu(user_token, TextAddProductName.getText().toString(), dish_sort_id, TextAddOriginalPrice.getText().toString(), TextAddDiscount.getText().toString(), ImageArray + "", TextAddIntroduce.getText().toString(), strArray + "", OptionalArray + "", new Subscriber<VerificationBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(VerificationBean verificationBean) {
                if (verificationBean.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast(verificationBean.getReturn_msg());
                    finish();
                } else {
                    JUtils.Toast(verificationBean.getReturn_msg());
                }
            }
        });
    }

    boolean ableGoNext() {
        if (TextUtils.isEmpty(TextAddProductName.getText().toString())) {
            JUtils.Toast("请输入品名");
            return false;
        } else if (TextUtils.isEmpty(TextAddOriginalPrice.getText().toString())) {
            JUtils.Toast("请输入菜品原价");
            return false;
        } else if (TextUtils.isEmpty(TextAddDiscount.getText().toString())) {
            JUtils.Toast("请输入优惠金额");
            return false;
        } else if (TextUtils.isEmpty(ImageArray + "")) {
            JUtils.Toast("请上传菜品图片");
            return false;
        } else if (TextUtils.isEmpty(TextAddIntroduce.getText().toString())) {
            JUtils.Toast("请输入菜品介绍");
            return false;
        } else if (TextUtils.isEmpty(strArray + "")) {
            JUtils.Toast("请输入必填项");
            return false;
        } else if (TextUtils.isEmpty(OptionalArray + "")) {
            JUtils.Toast("请输入选填项");
            return false;
        }
        return true;
    }


    void OnClick() {
        bottomDialog.show();
        XiCe_pickPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageUri = getImageCropUri();
                takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
                bottomDialog.dismiss();
            }
        });
        XiJi_takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageUri = getImageCropUri();
                takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                bottomDialog.dismiss();
            }
        });
        cancel_TextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        String iconPath = result.getImage().getOriginalPath();
        if (StrChoice.equals("1")) {
            Glide.with(AddMenuActivity.this).load(iconPath)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                    .skipMemoryCache(true)
                    .into(ImageAdd1);
        } else if (StrChoice.equals("2")) {
            Glide.with(AddMenuActivity.this).load(iconPath)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                    .skipMemoryCache(true)
                    .into(ImageAdd2);
        } else if (StrChoice.equals("3")) {
            Glide.with(AddMenuActivity.this).load(iconPath)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                    .skipMemoryCache(true)
                    .into(ImageAdd3);
        }
        getUploadImage(iconPath);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Toast.makeText(AddMenuActivity.this, "Error:" + msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void takeCancel() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    private void initData() {
        //获取TakePhoto实例
        takePhoto = getTakePhoto();
        //设置裁剪参数
        cropOptions = new CropOptions.Builder().setAspectX((int) 0.5).setAspectY((int) 0.5).setWithOwnCrop(false).create();
        //设置压缩参数
        compressConfig = new CompressConfig.Builder().setMaxSize(1 * 1).setMaxPixel(1).create();
        takePhoto.onEnableCompress(compressConfig, true);  //设置为需要压缩
    }

    //获得照片的输出保存Uri
    private Uri getImageCropUri() {
        File Gallery = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!Gallery.getParentFile().exists()) Gallery.getParentFile().mkdirs();
        return Uri.fromFile(Gallery);
    }

    public void getUploadImage(String imageUri) {
        Uri uri = getImageContentUri(AddMenuActivity.this, getFilePath(imageUri));
        if (uri == null) {
            Toast.makeText(this, "你没有选择任何图片", Toast.LENGTH_LONG).show();
        } else {
            String path = null;
            String[] pojo = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(uri, pojo, null, null, null);
            if (cursor != null) {
                int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
                cursor.moveToFirst();
                path = cursor.getString(columnIndex);
                cursor.close();
                Log.e("takeSuccess", path + "");
            }
            if (path != null) {
                doUpload(path);
            }
        }
    }

    public static Uri getImageContentUri(Context context, java.io.File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    File getFilePath(String str) {
        File Gallery = new File(str);
        if (!Gallery.getParentFile().exists()) Gallery.getParentFile().mkdirs();
        return Gallery;
    }

    private void doUpload(final String pathName) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    //文件二进制数据
                    InputStream in = new FileInputStream(new File(pathName));
                    //普通字符串数据
                    Map<String, String> data = new HashMap<String, String>();
                    final String result = userService.dishUpload(in, data, pathName);
                    Log.i("asdasd", result);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getString("return_code").equals("SUCCESS")) {
                                    if (StrChoice.equals("1")) {
                                        for (int i = 0; i < ImageArray.size(); i++) {
                                            if (ImageArray.get(i).equals("{\"pic_src\":\"" + StrImage_Add1 + "\"}"))
                                                ImageArray.remove(i);
                                        }
                                        StrImage_Add1 = jsonObject.getString("return_body");
                                    } else if (StrChoice.equals("2")) {
                                        for (int i = 0; i < ImageArray.size(); i++) {
                                            if (ImageArray.get(i).equals("{\"pic_src\":\"" + StrImage_Add2 + "\"}"))
                                                ImageArray.remove(i);
                                        }
                                        StrImage_Add2 = jsonObject.getString("return_body");
                                    } else if (StrChoice.equals("3")) {
                                        for (int i = 0; i < ImageArray.size(); i++) {
                                            if (ImageArray.get(i).equals("{\"pic_src\":\"" + StrImage_Add3 + "\"}"))
                                                ImageArray.remove(i);
                                        }
                                        StrImage_Add3 = jsonObject.getString("return_body");
                                    }
                                    ImageArray.add("{\"pic_src\":\"" + jsonObject.getString("return_body") + "\"}");
                                    System.out.println(ImageArray);
                                    Toast.makeText(AddMenuActivity.this, jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();
                                } else if (jsonObject.getString("return_code").equals("FAIL")) {
                                    Toast.makeText(AddMenuActivity.this, jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(AddMenuActivity.this, "上传错误", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }


}
